package cn.net.withub.dataCollector.web.collector;

import cn.net.withub.dataCollector.common.utils.CommonProperties;
import cn.net.withub.dataCollector.common.utils.CreateNewKey;
import cn.net.withub.dataCollector.common.utils.SpringBeanHelper;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.SocketException;
import java.net.URL;
import javax.activation.DataHandler;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import sun.misc.BASE64Encoder;
//import org.apache.cxf.jaxrs.ext.multipart.InputStreamDataSource;

public class FtpUtil {
	private static String[] ips = null;
	private static String[] ports = null;
	private static String[] users = null;
	private static String[] pwds = null;

    private static String ip = "120.79.157.134";
    private static String port = "21";
    private static String user = "anonymous";
    //private static String user = "ftpuser";
    private static String pwd = "953868249";


	//private static final CommonProperties commonProperties = (CommonProperties) SpringBeanHelper.getBean("commonProperties");
    //
	//static {
	//	ips = commonProperties.ftpAddress.trim().split(",");
	//	ports = commonProperties.ftpPort.trim().split(",");
	//	users = commonProperties.ftpUserName.trim().split(",");
	//	pwds = commonProperties.ftpPassword.trim().split(",");
	//}

    public static void main(String[] args) throws Exception{
        String ftpHost = "120.79.157.134";
        String ftpUserName = "ftpuser";
        ftpUserName = "anonymous";
        String ftpPassword = "953868249";
        int ftpPort = 21;
        //String ftpPath = "/ftpfile/lwj";//linux
        String ftpPath = "/home/lwj/111.jpg";//linux
        String ftpPath1 = "/home/lwj/";//linux
        //String ftpPath = "test2/";
        //String localPath = "F:\\zhanghu.txt";//windows
        String localPath = "G:\\image";//windows
        String fileName = "00.jpg";
        download(ftpPath1, "111.jpg");

        //downloadFtpFile(ftpHost, ftpUserName, ftpPassword, ftpPort, ftpPath, localPath, fileName);
        //上传一个文件
        /*try {
            //getImage("https://inews.gtimg.com/newsapp_match/0/4345600354/0", "");
            getImage("https://imgsa.baidu.com/news/q%3D100/sign=e11636363501213fc9334adc64e636f8/18d8bc3eb13533faee8d91c1a4d3fd1f41345b21.jpg", "");
        } catch (IOException e) {
            e.printStackTrace();
        }*/
        /*try{

            FileInputStream in=new FileInputStream(new File(localPath));
            boolean test = FtpTest.uploadFile(ftpHost, ftpUserName, ftpPassword, ftpPort, ftpPath, fileName,in);
            System.out.println(test);
        } catch (FileNotFoundException e){
            e.printStackTrace();
        }*/

        /*//在FTP服务器上生成一个文件，并将一个字符串写入到该文件中
        try {
            InputStream input = new ByteArrayInputStream("test ftp 测试".getBytes("UTF-8"));
            boolean flag = FtpTest.uploadFile(ftpHost, ftpUserName, ftpPassword, ftpPort, ftpPath, fileName,input);;
            System.out.println(flag);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }*/

        /*localPath = "E:\\";
        ftpPath="index.html";
        //下载一个文件
        FtpTest.downloadFtpFile(ftpHost, ftpUserName, ftpPassword, ftpPort, ftpPath, localPath, fileName);*/
    }
    /**
     * 获取FTPClient对象
     *
     * @param ftpHost     FTP主机服务器
     * @param ftpPassword FTP 登录密码
     * @param ftpUserName FTP登录用户名
     * @param ftpPort     FTP端口 默认为21
     * @return
     */
    public static FTPClient getFTPClient(String ftpHost, String ftpUserName, String ftpPassword, int ftpPort) {
        FTPClient ftpClient = new FTPClient();
        try {
            ftpClient = new FTPClient();
            ftpClient.connect(ftpHost, ftpPort);// 连接FTP服务器
            ftpClient.login(ftpUserName, ftpPassword);// 登陆FTP服务器
            ftpClient.setControlEncoding("GBK");
            ftpClient.setDataTimeout(60000);
            if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                System.out.println("未连接到FTP，用户名或密码错误。");
                ftpClient.disconnect();
            } else {
                System.out.println("FTP连接成功。");
            }
        } catch (SocketException e) {
            e.printStackTrace();
            System.out.println("FTP的IP地址可能错误，请正确配置。");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("FTP的端口错误,请正确配置。");
        }
        return ftpClient;
    }


    /**
     * 从FTP服务器下载文件
     *
     * @param ftpHost FTP IP地址
     * @param ftpUserName FTP 用户名
     * @param ftpPassword FTP用户名密码
     * @param ftpPort FTP端口
     * @param ftpPath FTP服务器中文件所在路径 格式： ftptest/aa
     * @param localPath 下载到本地的位置 格式：H:/download
     * @param fileName 文件名称
     */
    public static void downloadFtpFile(String ftpHost, String ftpUserName,
                                       String ftpPassword, int ftpPort, String ftpPath, String localPath,
                                       String fileName) {

        FTPClient ftpClient = null;

        try {
            ftpClient = getFTPClient(ftpHost, ftpUserName, ftpPassword, ftpPort);
            ftpClient.setControlEncoding("GBK"); // 中文支持
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftpClient.enterLocalPassiveMode();
            ftpClient.changeWorkingDirectory(ftpPath);

            File localFile = new File(localPath + File.separatorChar + fileName);
            OutputStream os = new FileOutputStream(localFile);
            ftpClient.retrieveFile(fileName, os);
            os.close();
            ftpClient.logout();

        } catch (FileNotFoundException e) {
            System.out.println("没有找到" + ftpPath + "文件");
            e.printStackTrace();
        } catch (SocketException e) {
            System.out.println("连接FTP失败.");
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("文件读取错误。");
            e.printStackTrace();
        }

    }

    /**
     * ftp读取图片并转Base64
     * @param ftpUrl
     * @param sfzh
     * @return
     */
    public static String download(String ftpUrl,String sfzh){
        FTPClient ftpClient = new FTPClient();
        String ftpHost = "120.79.157.134";
        String ftpUserName = "ftpuser";
        ftpUserName = "anonymous";
        String ftpPassword = "953868249";
        int ftpPort = 21;
        //String ftpPath = "/ftpfile/lwj";//linux
        String ftpPath = "/home/lwj/111.jpg";//linux
        InputStream inputStream = null;
        String re=null;
        try {
            ftpClient.connect(ftpHost,ftpPort);
            ftpClient.login(ftpUserName, ftpPassword);
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            //是否成功登录服务器
            int reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect();
            }
            //跳转到指定目录
            ftpClient.changeWorkingDirectory(ftpUrl);
            //5.遍历下载的目录
            FTPFile[] fs = ftpClient.listFiles();
            for (FTPFile ff : fs){
                //解决中文乱码问题，两次解码
                byte[] bytes=ff.getName().getBytes("iso-8859-1");
                String fileName=new String(bytes,"utf-8");
                if(sfzh.equals(fileName)){
                    inputStream = ftpClient.retrieveFileStream(fileName);
                }
            }

            if (inputStream != null) {
                byte[] data=null;
                data=new byte[inputStream.available()];
                BASE64Encoder encoder=new BASE64Encoder();
                re=encoder.encode(data);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(ftpClient.isConnected()){
                try{
                    ftpClient.disconnect();
                }catch(IOException e){
                    e.printStackTrace();
                }
            }
            if(null != inputStream){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return re;
    }


    /**
     * Description: 向FTP服务器上传文件
     * @param ftpHost FTP服务器hostname
     * @param ftpUserName 账号
     * @param ftpPassword 密码
     * @param ftpPort 端口
     * @param ftpPath  FTP服务器中文件所在路径 格式： ftptest/aa
     * @param fileName ftp文件名称
     * @param input 文件流
     * @return 成功返回true，否则返回false
     */
    public static String uploadFile(String ftpHost, String ftpUserName,
                                     String ftpPassword, int ftpPort, String ftpPath,
                                     String fileName,InputStream input) {
        FTPClient ftpClient = null;
        String serverPath = "";
        try {
            int reply;
            ftpClient = getFTPClient(ftpHost, ftpUserName, ftpPassword, ftpPort);
            reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect();
                return serverPath;
            }
            ftpClient.setControlEncoding("GBK"); // 中文支持  UTF-8乱码
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);//设置文件类型（二进制）
            //这个方法的意思就是每次数据连接之前，ftp client告诉ftp server开通一个端口来传输数据。为什么要这样做呢，因为ftp server可能
            // 每次开启不同的端口来传输数据，但是在linux上，由于安全限制，可能某些端口没有开启，所以就出现阻塞。
            ftpClient.enterLocalPassiveMode();
            //changeWorkingDirectory比较奇怪 120.79.157.134下 必须在目录存在的情况下才会切换成功,在ftp根目录下切换  一层目录好像也不能切换成功   10.149.0.57下又正常
            changeMakeWorkingDir(ftpPath, ftpClient);
            ftpClient.storeFile(fileName, input);
            input.close();
            ftpClient.logout();
            serverPath = ftpPath + fileName;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return serverPath;
    }
    public static String getImage(String destUrl,String type) throws IOException {
        FileOutputStream fos = null;
        BufferedInputStream bis = null;
        HttpURLConnection httpUrl = null;
        URL url = null;
        byte[] buf = new byte[1024];
        int size = 0;
        String filePath = "";
        String serverFilePath = "";
        try{
            url = new URL(destUrl);
            httpUrl = (HttpURLConnection) url.openConnection();
            //遇到403   加上User-Agent避免403禁止访问情况
            httpUrl.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            httpUrl.connect();
            InputStream is = httpUrl.getInputStream();
            //写文件
            bis = new BufferedInputStream(is);
            // 如果不存在就创建文件夹
            String directoryPath = "/home/myapp/webCollector/temp/";
            //String directoryPath = "F:\\imageTest\\";
            if (!new File(directoryPath).exists()) {
                new File(directoryPath).mkdirs();
            }
            String ftpPath = "/news/img/";
            String fileName = "";
            if ("1".equals(type)) {
                fileName = new CreateNewKey().createId() + ".jpg";
            } else if ("wy".equals(type)) {
                fileName = new CreateNewKey().createId() + destUrl.substring(destUrl.lastIndexOf("."), destUrl.lastIndexOf("?"));
            } else {
                fileName = new CreateNewKey().createId()+destUrl.substring(destUrl.lastIndexOf("."),destUrl.length());
            }
            filePath = directoryPath+fileName;
            File file = new File(filePath);
            if(!file.exists()){
                file.createNewFile();
            }
            fos = new FileOutputStream(filePath);
            while ((size = bis.read(buf)) != -1){
                fos.write(buf, 0, size);
                //fos.flush();
            }

            //关闭流
            fos.close();
            bis.close();
            is.close();
            httpUrl.disconnect();
            FileInputStream in=new FileInputStream(new File(filePath));
            //上传至fastdfs服务器
            //serverFilePath = FastDfsUtil.Upload(filePath);
            serverFilePath= FtpUtil.uploadFile(ips[0], users[0], pwds[0], Integer.parseInt(ports[0]), ftpPath, fileName,in);
        }catch (Exception e){
            System.out.println("出错url:" + destUrl);
            e.printStackTrace();
        }finally {
            //删除文件
            if(!filePath.equals("")){
                File f = new File(filePath);
                if (f.exists()) {
                    f.delete();
                }
            }
        }
        return serverFilePath;
    }


    private static void changeMakeWorkingDir(String path, FTPClient ftpClient) throws IOException {
        String[] dirs = path.split("/");
        for (String dir : dirs) {
            dir = new String(dir.getBytes("GBK"), "iso-8859-1");
            if (dir != null && !"".equals(dir)) {
                ftpClient.makeDirectory(dir);//没有就创建目录返回true；已经有了就不创建了，返回fasle
                //ftpClient.cdUp();//当前目录上移一层。
            }
            ftpClient.changeWorkingDirectory(dir);//切换到指定目录
        }
    }
	
    /**
	 * 采用流上传，只能上传到第一个FTP
	 * @param in
	 * @param filePath
	 * @return
	 */
	public static void uploadFtp(InputStream in, String filePath)throws Exception{
		if(ips!=null&&ips.length>0){
			if (ips[0] != null && !ips[0].trim().equals("")) {
				ftpUpload(in,filePath, ips[0],Integer.parseInt(ports[0].trim()), users[0],pwds[0]);
			}
		}
	}	
	
	/**
	 * 上传文件到FTP
	 * @param wjdata
	 * @param filePath
	 * @return
	 */
	public static void uploadFtp(byte[] wjdata, String filePath)throws Exception{
		if(ips!=null&&ips.length>0){
			for (int i = 0; i < ips.length; i++) {
				if (ips[i] != null && !ips[i].trim().equals("")) {
					ftpUpload(new ByteArrayInputStream(wjdata.clone()),filePath, ips[i],Integer.parseInt(ports[i].trim()), users[i],pwds[i]);
				}
			}
		}
	}
	
	/**
	 * 上传文件到FTP
	 * @param sourcePath
	 * @param filePath
	 * @return
	 */
	public static void uploadFtp(String sourcePath, String filePath)throws Exception{
		for (int i = 0; i < ips.length; i++) {
			if (ips[i] != null && !ips[i].trim().equals("")) {
				ftpUpload(new FileInputStream(sourcePath), filePath,ips[i], Integer.parseInt(ports[i].trim()),users[i], pwds[i]);
			}
		}
	}

	public static void ftpUpload(InputStream in, String filePath,String ftpIp, Integer ftpPort, String ftpUser, String ftpPwd)throws Exception {
		FTPClient ftpClient = new FTPClient();
		if (connectServer(ftpClient, ftpIp, ftpPort, ftpUser, ftpPwd)) {
			ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
			ftpClient.enterLocalPassiveMode();
			ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
			ftpClient.setControlEncoding("UTF-8");
			filePath = new String(filePath.getBytes("UTF-8"),"iso-8859-1");
            System.out.println("filePath-------------"+filePath);
            if (createDir(filePath, ftpClient)) {
				if (!ftpClient.storeFile(filePath, in)) {
					closeConnect(ftpClient);
					throw new Exception("FTP上传失败！");
				}
				in.close();
				closeConnect(ftpClient);
			}
		}else{
			closeConnect(ftpClient);
			throw new Exception("FTP连接失败！");
		}
	}
	
	
	public static void deleteFtp(String filePath,int type)throws Exception{
		if(ips!=null&&ips.length>0){
			if (ips[0] != null && !ips[0].trim().equals("")) {
				ftpDelete(filePath,type,ips[0],Integer.parseInt(ports[0].trim()), users[0],pwds[0]);
			}
		}
	}	
	
	/**
	 * 删除ftp文件
	 * @param filePath
	 * @param ftpIp
	 * @param ftpPort
	 * @param ftpUser
	 * @param ftpPwd
	 * @throws Exception
	 */
	public static void ftpDelete(String filePath,int type,String ftpIp, Integer ftpPort, String ftpUser, String ftpPwd)throws Exception {
		FTPClient ftpClient = new FTPClient();
		if (connectServer(ftpClient, ftpIp, ftpPort, ftpUser, ftpPwd)) {
			ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
			ftpClient.enterLocalPassiveMode();
			ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
			ftpClient.setControlEncoding("UTF-8");
			filePath = new String(filePath.getBytes("UTF-8"),"iso-8859-1");
			
			try {
				if(type==1){
					deleteFile(ftpClient,filePath);
				}else if(type==2){
					removeDirectory(ftpClient,filePath,true);
				}
			} catch (Exception e) {
				closeConnect(ftpClient);
				throw new Exception("删除文件失败！");
			}
		}else{
			closeConnect(ftpClient);
			throw new Exception("FTP连接失败！");
		}
		
		//执行完后关闭ftp连接
		closeConnect(ftpClient);
	}
	
	/**
	 * 删除目录下所有文件
	 * @param ftpClient
	 * @param path
	 * @param isAll
	 * @return
	 * @throws IOException
	 */
	public static boolean removeDirectory(FTPClient ftpClient,String path, boolean isAll) throws IOException{  
		if (!isAll) {  
            return ftpClient.removeDirectory(path);  
        }  
  
        FTPFile[] ftpFileArr = ftpClient.listFiles(path);  
        if (ftpFileArr == null || ftpFileArr.length == 0) { 
            return ftpClient.removeDirectory(path);  
        }  
        
        for (FTPFile ftpFile : ftpFileArr) {  
            String name = ftpFile.getName(); 
            if (ftpFile.isDirectory()) {  
                removeDirectory(ftpClient,path + "/" + name, true);  
            } else if (ftpFile.isFile()) {  
            	ftpClient.deleteFile(path + "/" + name);  
            } 
        }  
        return ftpClient.removeDirectory(path); 
	}  
	
	/**
     * 删除服务器上的文件
     *  @param ftpClient
     * @param pathName
     * @return
     * @throws IOException
     */
    public static boolean deleteFile(FTPClient ftpClient,String pathName) throws IOException {  
        return ftpClient.deleteFile(pathName);  
    } 
	
	/**
	 * 解析上传路径，创建DIRS的路径中的所有目录
	 * 
	 * @param path
	 * @param ftpClient
	 * @return
	 * @throws Exception
	 */
	private static boolean createDir(String path, FTPClient ftpClient)
			throws Exception {
		String dir = new File(path).getParentFile().getPath();
		if (!ftpClient.changeWorkingDirectory(dir)) {
			String[] dirs = dir.replace("\\", "/").split("/");
			String dir_tem = "";
			for (int i = 0; i < dirs.length; i++) {
				if (dirs[i]==null||dirs[i].trim().length() < 1) {
					continue;
				}
				dir_tem += "/" + dirs[i];
				makeDirectory(dir_tem, ftpClient);
			}
		}
		changeWorkingDirectory("/", ftpClient);// 回到FTP根目录
		return true;
	}


	// 创建子目录
	private static boolean makeDirectory(String dir, FTPClient ftpClient)
			throws Exception {
		return ftpClient.makeDirectory(dir);
	}

	// 改变目录的顶级路劲
	private static void changeWorkingDirectory(String directory,
			FTPClient ftpClient) throws Exception {
        boolean qhml = ftpClient.changeWorkingDirectory(directory);
        System.out.println("切换目录:"+qhml);
    }

	// 连接FTP
	public static boolean connectServer(FTPClient ftpClient, String ftpIp,Integer ftpPort, String ftpUser, String ftpPwd)throws Exception{
		boolean flag = false;
			ftpClient.setControlEncoding("GBK");
			ftpClient.connect(ftpIp);
			ftpClient.setDefaultPort(ftpPort);
			ftpClient.login(ftpUser, ftpPwd);
			int reply = ftpClient.getReplyCode();
			ftpClient.setDataTimeout(60000);
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftpClient.disconnect();
				flag = false;
			} else {
				flag = true;
			}
		return flag;
	}

	/**
	 * 关闭FTP
	 * 
	 * @param ftpClient
	 */
	public static void closeConnect(FTPClient ftpClient) {
		try {
			if (ftpClient != null) {
				ftpClient.logout();
				ftpClient.disconnect();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static byte[] getByteFromFile(InputStream input) {
		try {
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			byte[] b = new byte[1024];
			int n;
			while ((n = input.read(b)) != -1)
				out.write(b, 0, n);
			byte[] returnBy = out.toByteArray();
			input.close();
			out.close();
			return returnBy;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 下载ftp文件到本地
	 * @throws Exception 
	 * @throws IOException 
	 * @throws UnsupportedEncodingException 
	 * @throws NumberFormatException 
	 */
	public static void downloadFtpFile(String ftpPath,String filePath,String fileName) throws Exception{
		if(ips!=null&&ips.length>0){
			if (ips[0] != null && !ips[0].trim().equals("")) {
				FTPClient ftpClient = new FTPClient();
				if (connectServer(ftpClient, ips[0], Integer.parseInt(ports[0].trim()), users[0], pwds[0])) {
					ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
					ftpClient.enterLocalPassiveMode();
					ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
					ftpClient.setControlEncoding("UTF-8");
					ftpPath = new String(ftpPath.getBytes("UTF-8"),"iso-8859-1");
					//filePath = new String(filePath.getBytes("UTF-8"),"iso-8859-1");
					
					try {
						//读取ftp原文件
						ftpClient.setBufferSize(1024); 
						ByteArrayOutputStream fos=new ByteArrayOutputStream();
						boolean bool = ftpClient.retrieveFile(ftpPath, fos);
						//System.out.println(bool+" : "+fileName+": "+fos.toByteArray().length+" : "+ftpPath);
						ByteArrayInputStream in=new ByteArrayInputStream(fos.toByteArray());
						File f = new File(filePath);
						if(!f.exists()){
							f.mkdirs();
						}
						
						byte[] buf = new byte[1024];  
			            int bufsize = 0;
						FileOutputStream out = new FileOutputStream(filePath+fileName);  
			            while ((bufsize = in.read(buf, 0, buf.length)) != -1) {  
			            	out.write(buf, 0, bufsize);  
			            }  
			            
			            //关闭流
			            out.close();  
			            in.close();  
			            System.out.println("下载文件"+fileName+"完成!") ;
					} catch (Exception e) {
						e.printStackTrace();
					}
				}else{
					closeConnect(ftpClient);
					throw new Exception("FTP连接失败！");
				}
			}
		}
	}
	
	public static void getSteam(String ftpPath,String fileName,HttpServletResponse response,HttpServletRequest request) throws Exception{
		if(ips!=null&&ips.length>0){
			if (ips[0] != null && !ips[0].trim().equals("")) {
				FTPClient ftpClient = new FTPClient();
				if (connectServer(ftpClient, ips[0], Integer.parseInt(ports[0].trim()), users[0], pwds[0])) {
					ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
					ftpClient.enterLocalPassiveMode();
					ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
					ftpClient.setControlEncoding("UTF-8");
					ftpPath = new String(ftpPath.getBytes("UTF-8"),"iso-8859-1");
					try {
						//读取ftp原文件
						ftpClient.setBufferSize(1024); 
						ByteArrayOutputStream fos=new ByteArrayOutputStream();
						boolean bool = ftpClient.retrieveFile(ftpPath, fos);
						//System.out.println(bool+" : "+fileName+": "+fos.toByteArray().length+" : "+ftpPath);
						ByteArrayInputStream in=new ByteArrayInputStream(fos.toByteArray());
						//设置文件MIME类型  
				        response.setContentType(request.getSession().getServletContext().getMimeType(fileName));  
				        //设置Content-Disposition  
				        response.setHeader("Content-Disposition", "attachment;filename="+fileName);  
				        OutputStream out = response.getOutputStream(); 
				        //写文件  
				        int b;  
				        while((b=in.read())!= -1)  
				        {  
				            out.write(b);  
				        }  
				          
				        in.close();  
				        out.close();  
					  } catch (Exception e) {
						e.printStackTrace();
					}
				}else{
					closeConnect(ftpClient);
					throw new Exception("FTP连接失败！");
				}
			}
		}
	}
	public static DataHandler getFtpFileToDataSource(String ftpPath,String fileName) throws Exception{
		DataHandler dh=null;
		if(ips!=null&&ips.length>0){
			if (ips[0] != null && !ips[0].trim().equals("")) {
				FTPClient ftpClient = new FTPClient();
				if (connectServer(ftpClient, ips[0], Integer.parseInt(ports[0].trim()), users[0], pwds[0])) {
					ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
					ftpClient.enterLocalPassiveMode();
					ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
					ftpClient.setControlEncoding("UTF-8");
					ftpPath = new String(ftpPath.getBytes("UTF-8"),"iso-8859-1");
					try {
						//读取ftp原文件
						ftpClient.setBufferSize(1024); 
						ByteArrayOutputStream fos=new ByteArrayOutputStream();
						boolean bool = ftpClient.retrieveFile(ftpPath, fos);
						//System.out.println(bool+" : "+fileName+": "+fos.toByteArray().length+" : "+ftpPath);
						InputStream in=new ByteArrayInputStream(fos.toByteArray());
						//dh=new DataHandler( new InputStreamDataSource(in,null));
				       in.close();
					  } catch (Exception e) {
						e.printStackTrace();
					}
				}else{
					closeConnect(ftpClient);
					throw new Exception("FTP连接失败！");
				}
			}
		}
	return dh;
	}

}
